<template>
    <div class="pie-chart" ref="chartContainer">
      <div v-if="isEmptyData" class="empty-tip">暂无有效数据</div>
    </div>
  </template>
  
  <script>
  import * as echarts from 'echarts';
  
  // 颜色配置常量
  const COLOR_SCHEME = {
    employed: {
      start: '#36DBCA',
      end: '#2B8AFF'
    },
    unemployed: {
      start: '#FF7B89',
      end: '#FF3D71'
    }
  };
  
  export default {
    name: 'TotalPie',
    props: {
      chartData: {
        type: Object,
        required: true,
        default: () => ({
          graduateNum: 0,
          haveWorkNum: 0,
          noWorkNum: 0
        }),
        validator: value => {
          return ['graduateNum', 'haveWorkNum', 'noWorkNum'].every(prop => 
            prop in value && Number.isInteger(value[prop])
          );
        }
      }
    },
    data() {
      return {
        chart: null
      };
    },
    computed: {
      isEmptyData() {
        return this.chartData.graduateNum === 0;
      }
    },
    mounted() {
      this.$nextTick(() => {
        if (!this.isEmptyData) {
          this.initChart();
          window.addEventListener('resize', this.handleResize);
        }
      });
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.handleResize);
      if (this.chart) {
        this.chart.dispose();
      }
    },
    methods: {
      initChart() {
        try {
          this.chart = echarts.init(this.$refs.chartContainer,null,{
            width: 800,
            height: 380
          });
          this.updateChart();
          
          // 添加点击事件
          this.chart.on('click', params => {
            this.$emit('slice-click', params);
          });
        } catch (error) {
          console.error('图表初始化失败:', error);
        }
      },
  
      handleResize() {
        if (this.chart) {
          this.chart.resize();
        }
      },
  
      generateGradient(colorSet) {
        return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: colorSet.start },
          { offset: 1, color: colorSet.end }
        ]);
      },
  
      updateChart() {
        if (!this.chart) return;
  
        const { graduateNum, haveWorkNum, noWorkNum } = this.chartData;
        const total = graduateNum || 1;
  
        const option = {
          title: {
            text: '毕业生就业率',
            subtext: `总毕业生数：${graduateNum.toLocaleString()}`,
            left: 'center',
            textStyle: {
              fontSize: 18,
              color: '#2c3e50'
            }
          },
          tooltip: {
            trigger: 'item',
            backgroundColor: 'rgba(0,0,0,0.8)',
            borderWidth: 0,
            textStyle: {
              color: '#fff',
              fontSize: 14
            },
            formatter: ({ name, value, percent }) => {
              const rate = ((value / total) * 100).toFixed(1);
              return `${name}<br>数量: ${value.toLocaleString()}<br>占比: ${rate}% (${percent}%)`;
            }
          },
          legend: {
            orient: 'vertical',
            left: 'left',
            top: 'middle',
            itemGap: 20,
            textStyle: {
              color: '#666',
              fontSize: 12
            },
            formatter: name => {
              const value = this.chartData[name === '已就业' ? 'haveWorkNum' : 'noWorkNum'];
              return `${name}  ${value.toLocaleString()}`;
            }
          },
          series: [{
            name: '就业状态',
            type: 'pie',
            radius: ['45%', '75%'],
            center: ['50%', '55%'],
            avoidLabelOverlap: true,
            hoverAnimation: true,
            label: {
              show: true,
              fontSize: 12,
              fontWeight: 'normal',
              color: '#444',
              formatter: ({ name, percent }) => 
                `${name}\n${percent}%`
            },
            itemStyle: {
              borderRadius: 6,
              borderColor: '#fff',
              borderWidth: 3
            },
            data: [
              {
                value: haveWorkNum,
                name: '已就业',
                itemStyle: {
                  color: this.generateGradient(COLOR_SCHEME.employed)
                }
              },
              {
                value: noWorkNum,
                name: '未就业',
                itemStyle: {
                  color: this.generateGradient(COLOR_SCHEME.unemployed)
                }
              }
            ],
            animationType: 'scale',
            animationEasing: 'elasticOut',
            animationDuration: 1200,
            animationDelay: (idx) => idx * 150
          }]
        };
  
        this.chart.setOption(option);
      }
    },
    watch: {
      chartData: {
        handler(newVal) {
          if (this.isEmptyData && this.chart) {
            this.chart.dispose();
            this.chart = null;
          } else if (!this.chart) {
            this.initChart();
          } else {
            this.updateChart();
          }
        },
        deep: true
      }
    }
  };
  </script>
  
  <style scoped>
  .pie-chart {
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 4px 16px rgba(0,0,0,0.08);
    position: relative;
  }
  
  .empty-tip {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: #999;
    font-size: 16px;
  }
  </style>